GLOBAL.setmetatable(env, { __index = function(t, k) return GLOBAL.rawget(GLOBAL, k) end })
GLOBAL.NUTSAPI = env
local _G = GLOBAL

modimport("scripts/nuts_linkmod.lua")                    -- 判断是否开启某些mod
TUNING.NUTS_LANGUAGE = GetModConfigData("languages")     -- 获取配置:语言
TUNING.SEASONAL_FOOD = GetModConfigData("Seasonal_Food") -- 获取配置:季节料理是否随时可做

PrefabFiles =
{
    "crispnuts_buffs",  -- buff
    "nuts_buffs",       -- buff(Gyde:原来的码师的那种写法我用着不习惯,另外起一个预制体文件)
    "crispynuts_food",  -- 食物
    "crispynuts_light", -- 1个发光的FX
    "nuts_beebox",      -- 松树盆
}

-- 双向联动所以在食趣开启之后,本mod关闭对方mod的内容,减少不必要的重复加载
local tf_spices =
{
    "nuts_spices",       -- 咖啡粉联动食趣
    "nuts_tf_buffs",     -- 食趣的buff
    "nuts_spices_foods", -- mod调味料理
}

if not _G.NUTS_SETS.ENABLEDMODS["tastefun"] then
    for k, v in pairs(tf_spices) do
        table.insert(PrefabFiles, v)
    end
end

Assets =
{
    Asset("ANIM", "anim/nutsfood.zip"),
    Asset("ANIM", "anim/nutsfood2.zip"),
    Asset("ANIM", "anim/nutsfood3.zip"), -- 食趣联动料理
    Asset("ANIM", "anim/swap_candybag.zip"),

    Asset("ATLAS", "images/nuts_inventoryimages.xml"), -- 物品栏贴图集
    Asset("IMAGE", "images/nuts_inventoryimages.tex"),
    Asset("ATLAS_BUILD", "images/nuts_inventoryimages.xml", 256),
}

local seg_time = 30
local mins = seg_time * 2
TUNING.NUTSBUFF_SPPED_DURATION = 4 * mins
TUNING.NUTSBUFF_SPPED2_DURATION = 6 * mins
TUNING.NUTSBUFF_SPPED3_DURATION = 4 * mins
TUNING.NUTSBUFF_WORK_DURATION = 4 * mins
TUNING.NUTSBUFF_STRENGTH_DURATION = 8 * mins
TUNING.NUTSBUFF_MOISTURE_DURATION = 6 * mins
TUNING.NUTSBUFF_SANITY_DURATION = mins
TUNING.NUTSBUFF_OSMANTHUS_SANITY_DURATION = 2 * mins

TUNING.NUTSBUFF_MACCHIATO_DURATION = 16 * mins      -- 松果玛奇朵
TUNING.NUTSBUFF_LATTE_BUTTER_DURATION = 12 * mins   -- 黄油拿铁
TUNING.NUTSBUFF_SANITY_MOONCAKE_DURATION = 2 * mins -- 月饼
TUNING.NUTS_BARLEYTEA_TEMPERATURE = {
    SPRING = 30,
    SUMMER = 10,
    AUTUMN = 30,
    WINTER = 50
}
TUNING.NUTS_BEEFALOFEED_DOMESTICATION = 0.01

TUNING.NUTSBUFF_SPEED1_MULT = 1 + (GetModConfigData("NUTS SPEED1") or 0.2)
TUNING.NUTSBUFF_SPEED2_MULT = 1 + (GetModConfigData("NUTS SPEED2") or 0.5)
TUNING.NUTSBUFF_SPEED3_MULT = 1 + 0.1
TUNING.NUTSBUFF_STRENGTH_MULT = 1.1

TUNING.NUTS_BEEBOX_MAX_PRODUCE = 20
TUNING.NUTS_BEEBOX_GROW_TIME = TUNING.TOTAL_DAY_TIME * 2

if not _G.NUTS_SETS.ENABLEDMODS["tastefun"] then
    modimport("scripts/nuts_tf_actions.lua") -- 调味动作
end

modimport("scripts/nuts_globalfn.lua")         -- 全局函数
modimport("scripts/crispynuts_containers.lua") -- 本mod容器
modimport("scripts/crispynuts_recipes.lua")    -- 本mod制作配方

-- 松果 不可食用 具有0.25水果度，1坚果度
AddIngredientValues({ "pinecone" }, { inedible = 1, crispynuts = 1 }, false, false)
local foods = require("crispynuts_food")
for k, recipe in pairs(foods) do
    table.insert(Assets, Asset("ATLAS", "images/cookbook_images/" .. k .. ".xml"))
    table.insert(Assets, Asset("IMAGE", "images/cookbook_images/" .. k .. ".tex"))

    AddCookerRecipe("cookpot", recipe)
    AddCookerRecipe("portablecookpot", recipe)
    AddCookerRecipe("archive_cookpot", recipe)

    if recipe.card_def then
        AddRecipeCard("cookpot", recipe)
    end
end

-- 兼容调味粉
GenerateSpicedFoods(foods)
local spicedfoods = require("spicedfoods")
for k, recipe in pairs(spicedfoods) do
    if recipe.basename and foods[recipe.basename] then
        if not recipe.nospice then
            AddCookerRecipe("portablespicer", recipe, true)
        end
    end
end

AddPrefabPostInit("monkey", function(inst)
    if not TheWorld.ismastersim then
        return inst
    end

    local FindTargetOfInterestTask = inst.FindTargetOfInterestTask
    if not FindTargetOfInterestTask then return inst end
    if not type(FindTargetOfInterestTask) == "Periodic" then return end
    local FindTargetOfInterest = FindTargetOfInterestTask.fn
    if not FindTargetOfInterestTask.fn then return inst end
    FindTargetOfInterestTask.fn = function(inst, ...)
        FindTargetOfInterest(inst, ...)
        if inst.harassplayer and inst.harassplayer:HasTag("nutprotect_banana") then
            inst.harassplayer = nil
        end
    end

    return inst
end)

local function equipped(inst)
    return (inst.replica and inst.replica.equippable and inst.replica.equippable:IsEquipped())
        or (inst.components and inst.components.equippable and inst.replica.equippable:IsEquipped())
end
AddComponentPostInit("playeractionpicker", function(PlayerActionPicker)
    local _GetRightClickActions = PlayerActionPicker.GetRightClickActions
    function PlayerActionPicker:GetRightClickActions(position, target, spellbook, ...)
        local actions = _GetRightClickActions(self, position, target, spellbook, ...)
        local useitem = self.inst.replica.inventory:GetActiveItem()
        if actions and target ~= nil and useitem ~= nil and useitem.prefab == "nuts_candybag" then
            actions = self:SortActionList({ ACTIONS.EQUIP }, target, useitem)
        end

        return actions or {}
    end

    local _GetInventoryActions = PlayerActionPicker.GetInventoryActions
    function PlayerActionPicker:GetInventoryActions(useitem, right, ...)
        local actions = _GetInventoryActions(self, useitem, right, ...)
        if actions and useitem and useitem.prefab == "nuts_candybag" and equipped(useitem) then
            actions = self:SortActionList({ ACTIONS.EAT }, nil, useitem)
        end

        return actions or {}
    end
end)

NUTS_RegisterInventoryItemAtlas("images/nuts_inventoryimages.xml")

AddGlobalClassPostConstruct("entityscript", "EntityScript", function(EntityScript)
    local _GetAdjectivedName = EntityScript.GetAdjectivedName
    function EntityScript:GetAdjectivedName(...)
        local name = _GetAdjectivedName(self, ...)
        return self:HasTag("nuts_coffeed") and ConstructAdjectivedName(self, name, STRINGS.COFFEED) or name
    end
end)

AddComponentPostInit("edible", function(Edible)
    local _OnEaten = Edible.OnEaten
    function Edible:OnEaten(eater, ...)
        if eater and self.inst:HasTag("nuts_coffeed") then
            eater:AddDebuff("nutsbuff_speed3", "nutsbuff_speed3")
        end

        return _OnEaten(self, eater, ...)
    end
end)

AddComponentPostInit("sanity", function(Sanity)
    local _DoDelta = Sanity.DoDelta
    function Sanity:DoDelta(delta, ...)
        if self.inst.prefab == "yutu" and self.inst:HasTag("nuts_yutu") then
            delta = math.max(delta, 0)
        end

        return _DoDelta(self, delta, ...)
    end
end)

AddComponentPostInit("eater", function(Eater)
    local _PrefersToEat = Eater.PrefersToEat
    function Eater:PrefersToEat(food, ...)
        if self.inst:HasDebuff("nuts_buff_sticky_corn") then
            return false
        end
        return _PrefersToEat(self, food, ...)
    end
end)

-- 调味粉相关
if not _G.NUTS_SETS.ENABLEDMODS["tastefun"] then
    local nuts_tf_spicesfoods = require("nuts_tf_spicesfoods") -- 调味料理
    local cooking = require("cooking")
    -- 调味后料理额外三维恢复
    AddPrefabPostInitAny(function(inst)
        if not TheWorld.ismastersim then
            return
        end

        if inst:HasTag("spicedfood")
            and inst.components.edible and inst.components.edible.spice and nuts_tf_spicesfoods.NUTS_SPICES[inst.components.edible.spice]
            and inst.components.inventoryitem
        then
            local spicename = string.lower(inst.components.edible.spice)
            if spicename == "spice_tf_coffee_powder" then
                inst.components.edible.sanityvalue = inst.components.edible.sanityvalue + 10
            end
        end
    end)

    -- 调味后料理替换调味料贴图，但是我们的swapbuild不是spices，必须改成我们自己的动画build
    local OldOverrideSymbol = AnimState.OverrideSymbol
    AnimState.OverrideSymbol = function(self, symbol, swapbuild, swapsymbol, ...)
        if symbol == "swap_garnish" and swapbuild == "spices" and swapsymbol and nuts_tf_spicesfoods.NUTS_SPICES[string.upper(swapsymbol)] then
            swapbuild = "nuts_spices"
        end
        return OldOverrideSymbol(self, symbol, swapbuild, swapsymbol, ...)
    end

    -- Mod加载完后给所有食谱添加一遍新调料的料理，以下代码参考了风铃大佬的小穹，风铃大佬牛逼！
    local oldRegisterPrefabs = GLOBAL.ModManager.RegisterPrefabs

    GLOBAL.ModManager.RegisterPrefabs = function(self, ...)
        -- 这个时候 PrefabFiles文件还没有被加载

        for k, v in pairs(cooking.recipes) do
            if k and v and k ~= "portablespicer" then
                nuts_tf_spicesfoods.NUTS_GenerateSpicedFoods(v)
            end
        end
        -- 添加新的调味料理食谱
        for k, v in pairs(nuts_tf_spicesfoods.NutsGetNewRecipes()) do
            AddCookerRecipe("portablespicer", v)
        end
        oldRegisterPrefabs(self, ...)
    end
end

--设置语言
if TUNING.NUTS_LANGUAGE == "Chinese" then
    modimport("scripts/crispynuts_strings.lua")    --※中文
elseif TUNING.NUTS_LANGUAGE == "English" then
    modimport("scripts/crispynuts_strings_en.lua") --※英文
else
    modimport("scripts/crispynuts_strings.lua")
end

-- Mod加载完后
local oldRegisterPrefabs = GLOBAL.ModManager.RegisterPrefabs

GLOBAL.ModManager.RegisterPrefabs = function(self, ...)
    -- 这个时候 PrefabFiles文件还没有被加载
    if STRINGS.CHARACTERS.YUTU then
        STRINGS.CHARACTERS.YUTU.DESCRIBE.NUTS_SILVER_CRESCENT = STRINGS.NUTS.YUTU.NUTS_SILVER_CRESCENT
    end
    if STRINGS.CHARACTERS.WXW then
        STRINGS.CHARACTERS.WXW.DESCRIBE.NUTS_ECHOTIME = STRINGS.NUTS.WXW.NUTS_ECHOTIME
    end
    if STRINGS.CHARACTERS.GALLOP then
        STRINGS.CHARACTERS.GALLOP.DESCRIBE.NUTS_RABBIT_BLOOD = STRINGS.NUTS.GALLOP.NUTS_RABBIT_BLOOD
    end
    if STRINGS.CHARACTERS.RHINE then
        STRINGS.CHARACTERS.RHINE.DESCRIBE.NUTS_MEMORYBOUND = STRINGS.NUTS.RHINE.NUTS_MEMORYBOUND
    end
    if STRINGS.CHARACTERS.WUYI_LAMBRIS then
        STRINGS.CHARACTERS.WUYI_LAMBRIS.DESCRIBE.NUTS_FLAMEBORN = STRINGS.NUTS.WUYI_LAMBRIS.NUTS_FLAMEBORN
    end
    oldRegisterPrefabs(self, ...)
end
